var DBAccess = require('./db');
require('./../models/professor.model');

function ProfessorDAO() {
    var db = DBAccess.getInstance();
    var model = db.model('Professor');

    this.add = function(professor) {
        db.connect();
        professor.save(function(err) {
            if (err) throw err;
            db.disconnect();
        });
    }

    //FIXME change to remove by id
    this.remove = function(professor) {
        db.connect();
        model.remove({username: professor.username}, function(err) {
            if(err) throw err;
            db.disconnect();
        });
    }

    //FIXME change to search by id
    this.get = function(professor, callback) {
        db.connect();
        model.findOne({username: professor.username}, function(err, data) {
            if (!data) throw new Error('Not found');
            callback(err,data);
            db.disconnect();
        });
    }

    //FIXME change to search by id
    this.update = function(id, update) {
        db.connect();
        model.findOne({username: id}, function(err, old) {
            if (!old)
                throw new Error('Professor not found!');
            old.nome = update.nome || old.nome;
            old.email = update.email || old.email;
            old.username = update.username || old.username;
            old.password = update.password || old.password;
            old.roles = update.roles instanceof Array ? update.roles : old.roles;
            old.matricula = update.matricula || old.matricula;
            old.preferidas = update.preferidas instanceof Array ? update.preferidas : old.preferidas;
            old.disciplinas = update.disciplinas instanceof Array ? update.disciplinas : old.disciplinas;
            old.projetos = update.projetos instanceof Array ? update.projetos: old.projetos;
            old.departamento = update.departamento || old.departamento;
            old.save(function(err) {
                db.disconnect();
            });
        });
    }

    this.getAll = function(callback) {
        db.connect();
        if(typeof callback != 'function')
            throw new Error('give me a callback function!');
        model.find({}, function(err, all){
            callback(err, all);
            db.disconnect();
        });
    }


    this.getModel = function() {
        return new model();
    }
}

module.exports = ProfessorDAO;
